package com.lvcoding.auth2.auth.shizhan.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义client_id和client_secret相关异常
 *
 * @author wuyanshen
 */
@Component
public class CustomOauth2EntryPoint extends OAuth2AuthenticationEntryPoint {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (authException instanceof BadCredentialsException) {
            //如果是client_id和client_secret相关异常 返回自定义的数据格式
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            Map<String, Object> map = new HashMap<>();
            map.put("code", 401);
            map.put("msg", authException.getCause().getMessage());
            String jsonStr = objectMapper.writeValueAsString(map);
            response.getWriter().write(jsonStr);

        } else if (authException instanceof InsufficientAuthenticationException) {
            //如果是没有携带token
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            Map<String, Object> map = new HashMap<>();
            map.put("code", 401);
            map.put("msg", authException.getMessage());
            String jsonStr = objectMapper.writeValueAsString(map);
            response.getWriter().write(jsonStr);
        } else {
            super.commence(request, response, authException);
        }
    }
}
